# Create your views here.
import logging

from django.shortcuts import redirect
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.generics import RetrieveAPIView, CreateAPIView, ListAPIView
from . import constant
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

from tsukkomi.models import Tsukkomi, TsukkomiLike, TsukkomiCollect, Comment, CommentLike
from tsukkomi.serializers import TsukkomiListSerializer, TsukkomiInfoSerializer, TsukkomiCommentSerializer, \
    CreationCommentSerializer, CreationTsukkomiSerializer, TsukkomiCollectSerializer, CommentLikeSerializer
from tsukkomi.utils import ShareWB

logger = logging.getLogger("django")


class TsukkomiListView(ListAPIView):
    """查询吐槽列表"""
    serializer_class = TsukkomiListSerializer
    queryset = Tsukkomi.objects.all().order_by("-create_time")

    def list (self, request, *args, **kwargs):
        page = self.paginate_queryset(self.get_queryset())
        # 在分页序列化前对数据进行添加属性
        user = request.user
        print(user)
        for tsukkomi in page:
            TsukkomiLike_count = TsukkomiLike.objects.filter(tsukkomi_id=tsukkomi.id).count()  # 获取点赞数量
            tsukkomi.like_count = TsukkomiLike_count if TsukkomiLike_count else 0
            TsukkomiLike_collect = TsukkomiCollect.objects.filter(tsukkomi_id=tsukkomi.id,
                                                                  user_id=user.id if user.id else None).count()  # 获取是否收藏
            tsukkomi.is_collect = True if TsukkomiLike_collect else False
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        serializer = self.get_serializer(self.queryset, many=True)
        print(serializer.data)
        return Response(serializer.data)


class TsukkomiInfoView(RetrieveAPIView):
    """吐槽详情"""
    serializer_class = TsukkomiInfoSerializer
    queryset = Tsukkomi.objects.all()

    def retrieve (self, request, *args, **kwargs):
        instance = self.get_object()
        tsukkomi_id = kwargs.get("pk", None)
        TsukkomiLike_count = TsukkomiLike.objects.filter(tsukkomi_id=tsukkomi_id).count()  # 获取点赞数量
        TsukkomiLike_collect = Comment.objects.filter(tsukkomi_id=tsukkomi_id).count()  # 获取评论数量
        instance.like_count = TsukkomiLike_count if TsukkomiLike_count else 0
        instance.comment_count = TsukkomiLike_collect if TsukkomiLike_collect else 0
        serializer = self.get_serializer(instance)
        return Response(serializer.data)


class TsukkomiCommentView(ListAPIView):
    """获取评论数据"""
    serializer_class = TsukkomiCommentSerializer

    def get_queryset (self):
        tsukkomi_id = self.kwargs.get("pk", None)
        queryset = Comment.objects.filter(tsukkomi_id=tsukkomi_id).order_by("-create_time")
        return queryset

    def list (self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        page = self.paginate_queryset(queryset)
        for comment in page:
            comment_like_count = CommentLike.objects.filter(comment_id=comment.id).count()
            comment.like_count = comment_like_count if comment_like_count else 0
            comment.son_comments = Comment.objects.filter(parent=comment.id).order_by("-create_time")
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)


class CreationCommentView(CreateAPIView):
    """创建评论"""
    permission_classes = [IsAuthenticated]  # 必须经过验证
    serializer_class = CreationCommentSerializer


class CreationTsukkomiView(CreateAPIView):
    """发布吐槽"""
    permission_classes = [IsAuthenticated]  # 必须经过验证
    serializer_class = CreationTsukkomiSerializer


class TsukkomiCollectLikeView(CreateAPIView):
    """吐槽收藏与点赞"""
    permission_classes = [IsAuthenticated]  # 必须经过验证
    serializer_class = TsukkomiCollectSerializer

    def create (self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        response = Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
        if request.path_info == "/like/tsukkomi/":
            response.set_cookie('like_tsukkomi_' + str(serializer.data["tsukkomi"]),
                                'like_is_true_' + str(serializer.data["tsukkomi"]), max_age=constant.COOKIE_SAVE_TIME)
        return response


class CommentLikeView(CreateAPIView):
    """评论点赞"""
    permission_classes = [IsAuthenticated]  # 必须经过验证
    serializer_class = CommentLikeSerializer

    def create (self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        response = Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
        response.set_cookie('like_comment_' + str(serializer.data["comment"]),
                            'like_is_true_' + str(serializer.data["comment"]), max_age=constant.COOKIE_SAVE_TIME)
        return response


class ShareTsukkomiView(APIView):
    """获取登录页面"""

    def get (self, request):
        tsukkomi_id = request.query_params.get("tsukkomi_id")
        redis_conn = get_redis_connection("ShareWB")
        redis_conn.setex("tsukkomi_id", constant.TSUKKOMI_ID_SAVE_TIME, tsukkomi_id)
        sharewb = ShareWB()
        wb_url = sharewb.getWB_code()
        return Response({"wb_url": wb_url})  # 返回微博登录页面


class GetAccessTokenView(APIView):
    """获取微博AccessToken并分享"""

    def get (self, request):
        redis_conn = get_redis_connection("ShareWB")
        tsukkomi_id = redis_conn.get("tsukkomi_id")
        if not tsukkomi_id:
            return Response({"message": "分享内容获取失败,请重新分享"})
        code = request.query_params.get("code")  # 获取code
        if not code:
            return Response({"message": "code不存在"})
        sharewb = ShareWB()  # 创建分享微博的对象
        access_token = sharewb.getWB_token(code)
        tsukkomi = Tsukkomi.objects.get(id=int(tsukkomi_id.decode()))  # 获取分享内容
        print(tsukkomi)
        tsukkomi.share_count += 1  # 分享次数加1
        tsukkomi.save()
        status = tsukkomi.content
        wbidstr = sharewb.sharetsukkomi(access_token, status)  # 返回分享
        print(wbidstr)
        return Response({"wbuser_id": wbidstr})  # 返回微博用户id


class SelectCollectTsukkomi(ListAPIView):
    """查询收藏的吐槽"""
    permission_classes = [IsAuthenticated]  # 必须经过验证
    serializer_class = TsukkomiListSerializer

    def get_queryset (self):
        user_id = self.request.user.id
        queryset = TsukkomiCollect.objects.filter(user_id=user_id)
        tsukkomi_objs = list()
        for obj in queryset:
            tsukkomi_objs.append(obj.tsukkomi)
        return tsukkomi_objs

    def list (self, request, *args, **kwargs):
        page = self.paginate_queryset(self.get_queryset())
        # 在分页序列化前对数据进行添加属性
        for tsukkomi in page:
            TsukkomiLike_count = TsukkomiLike.objects.filter(tsukkomi_id=tsukkomi.id).count()  # 获取点赞数量
            tsukkomi.like_count = TsukkomiLike_count if TsukkomiLike_count else 0
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        serializer = self.get_serializer(self.queryset, many=True)
        return Response(serializer.data)
